import { defineStore } from 'pinia'
import { login, register } from '@/api/auth'
import router from '@/router'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: JSON.parse(localStorage.getItem('user')) || null,
    token: localStorage.getItem('token') || null
  }),
  
  actions: {
    // 添加 initialize 方法
    initialize() {
      // 从本地存储加载状态
      this.user = JSON.parse(localStorage.getItem('user')) || null
      this.token = localStorage.getItem('token') || null
    },
    
    async login(credentials) {
      const response = await login(credentials)
      this.user = response.user
      this.token = response.token
      
      localStorage.setItem('user', JSON.stringify(response.user))
      localStorage.setItem('token', response.token)
    },
    
    async register(userData) {
      await register(userData)
    },
    
    logout() {
      this.user = null
      this.token = null
      localStorage.removeItem('user')
      localStorage.removeItem('token')
      router.push('/login')
    }
  },
  
  getters: {
    isAuthenticated: (state) => !!state.token,
    userType: (state) => state.user?.type || null
  }
})
